package com.project.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dtyunxi.rest.RestCode;
import com.dtyunxi.rest.RestResponse;
import com.dtyunxi.util.JacksonUtil;
import com.dtyunxi.util.WeiXinApi;
import com.dtyunxi.vo.JsapiTicket;
import com.dtyunxi.vo.UserInfo;
import com.project.common.Constants;
import com.project.util.HttpRequest;
import com.project.util.WeiXinUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("api/weixin")
@Api(value = "api/weixin", description = "微信管理")
public class WeiXinController {
	
	private static final Logger logger = LoggerFactory.getLogger(WeiXinController.class);
	
	
	/**
	 * 获取微信sdk配置 所有需要使用JS-SDK的页面必须先注入配置信息， 否则将无法调用（同一个url仅需调用一次，对于变化url的SPA的web
	 * app可在每次url变化时进行调用, 目前Android微信客户端不支持pushState的H5新特性， 所以使用pushState来实现web
	 * app的页面会导致签名失败，此问题会在Android6.2中修复）。
	 * 
	 * @param url
	 * @return
	 */
	@ApiOperation(value = "获取微信sdk配置", notes = "获取微信sdk配置", response = Map.class)
	@RequestMapping(value = "config", method = RequestMethod.GET)
	public Map<String, String> getConfig(@ApiParam(required = true, name = "url", value = "url")@RequestParam String url) {
		String appId = Constants.WX_APPID;
		String secret = Constants.WX_APPSECRET;
		String jsapiTicket;
		Map<String, String> ret = null;
		if(StringUtils.isNotBlank(url)){
			JsapiTicket jsapiTicketObj = WeiXinUtil.getJsapiTicket(appId, secret);
			jsapiTicket = jsapiTicketObj.getTicket();
			logger.info("===============getConfig=================获取JsapiTicket:{}", jsapiTicket);
			ret = com.dtyunxi.util.WeiXinUtil.sign(jsapiTicket, url, appId);
		}
		return ret;
	}
	
	@ApiOperation(value = "获取用户openid", notes = "获取用户openid", response = String.class)
	@RequestMapping(value = "/openid", method = RequestMethod.GET)
	public RestResponse getUserOpenid(HttpServletRequest request, HttpServletResponse response) {
		String userAgent = request.getHeader("user-agent").toLowerCase();
		logger.info("------------------浏览器类型.userAgent:{}------------------", userAgent);
		if(userAgent.indexOf("micromessenger")>-1){//微信客户端获取openid
			String appId = Constants.WX_APPID;
			String code = request.getParameter("code");
			if(!StringUtils.isBlank(code)){//如果request中包括code，则是微信回调
				logger.info("===================跳转第二次======================");
				try {
					String secret = Constants.WX_APPSECRET;
					String openid = WeiXinUtil.getOpenid(appId, secret, code);
					logger.info("------------------获取到的openid:{}------------------", openid);
					if(!StringUtils.isBlank(openid)){
						return new RestResponse(openid);
					}
				} catch (Exception e) {
					logger.error(e.getMessage(),e);
				}
			}else{//oauth获取code
				logger.info("===================跳转第一次======================");
				String redirectUrl = HttpRequest.getRequestFullUriNoContextPath(request);//请求code的回调url
				System.out.println(redirectUrl);
				String url = WeiXinApi.getOAuthCodeUrl(Constants.WX_APPID, redirectUrl, "snsapi_base", "");
				HttpRequest.redirectHttpUrl(request,response, url);
			}
		}
		return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"非微信浏览器");
	}
	
	/*@ApiOperation(value = "获取微信用户信息", notes = "获取微信用户信息", response = UserInfo.class)
	@RequestMapping(value = "userinfo", method = RequestMethod.GET)
	public RestResponse getUserInfo(HttpServletRequest request,HttpServletResponse response) {
		String userAgent = request.getHeader("user-agent").toLowerCase();
		logger.info("------------------浏览器类型.userAgent:{}------------------", userAgent);
		if(userAgent.indexOf("micromessenger")>-1){//微信客户端获取openid
			String appId = Constants.WX_APPID;
			String code = request.getParameter("code");
			if(!StringUtils.isBlank(code)){//如果request中包括code，则是微信回调
				logger.info("===================跳转第二次======================");
				try {
					String secret = Constants.WX_APPSECRET;
					String openid = WeiXinUtil.getOpenid(appId, secret, code);
					logger.info("------------------获取到的openid:{}------------------", openid);
					if(!StringUtils.isBlank(openid)){
						UserInfo userInfo = com.dtyunxi.util.WeiXinUtil.getUserInfo(openid, WeiXinUtil.getAccessToken(appId, secret).getAccessToken());
						logger.info("------------------获取到的userInfo:{}------------------", userInfo);
						return new RestResponse(userInfo);
					}
				} catch (Exception e) {
					logger.error(e.getMessage(),e);
				}
			}else{//oauth获取code
				logger.info("===================跳转第一次======================");
				String redirectUrl = HttpRequest.getRequestFullUriNoContextPath(request);//请求code的回调url
				System.out.println(redirectUrl);
				String url = WeiXinApi.getOAuthCodeUrl(Constants.WX_APPID, redirectUrl, "snsapi_base", "");
				HttpRequest.redirectHttpUrl(request,response, url);
			}
		}
		return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"非微信浏览器");
	}*/
	
	/*@ApiOperation(value = "获取微信用户信息", notes = "获取微信用户信息", response = UserInfo.class)
	@RequestMapping(value = "userinfo", method = RequestMethod.GET)
	public RestResponse getUserInfo(HttpServletRequest request) {
		String userAgent = request.getHeader("user-agent").toLowerCase();
		logger.info("------------------浏览器类型.userAgent:{}------------------", userAgent);
		if(userAgent.indexOf("micromessenger")>-1){//微信客户端获取openid
			String appId = Constants.WX_APPID;
			String secret = Constants.WX_APPSECRET;
			String code = request.getParameter("code");
			String openid = WeiXinUtil.getOpenid(appId, secret, code);
			logger.info("------------------获取到的openid:{}------------------", openid);
			if(!StringUtils.isBlank(openid)){
				UserInfo userInfo = com.dtyunxi.util.WeiXinUtil.getUserInfo(openid, WeiXinUtil.getAccessToken(appId, secret).getAccessToken());
				logger.info("------------------获取到的userInfo:{}------------------", userInfo);
				return new RestResponse(userInfo);
				HttpRequest.redirectHttpUrl(request,response, url);
			}else{
				return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"获取用户信息失败");
			}
		}
		return new RestResponse(RestCode.RESULT_SYSTEM_ERROR,"非微信浏览器");
	}*/
	
	@ApiOperation(value = "获取微信用户信息判断跳转页面", notes = "获取微信用户信息判断跳转页面")
	@RequestMapping(value = "jump", method = RequestMethod.GET)
	public void getUserInfoToJumpPage(HttpServletRequest request, HttpServletResponse response) {
		String userAgent = request.getHeader("user-agent").toLowerCase();
		logger.info("------------------浏览器类型.userAgent:{}------------------", userAgent);
		if(userAgent.indexOf("micromessenger")>-1){//微信客户端获取openid
			String appId = Constants.WX_APPID;
			String secret = Constants.WX_APPSECRET;
			String code = request.getParameter("code");
			String openid = WeiXinUtil.getOpenid(appId, secret, code);
			logger.info("------------------获取到的openid:{}------------------", openid);
			if(!StringUtils.isBlank(openid)){
				UserInfo userInfo = com.dtyunxi.util.WeiXinUtil.getUserInfo(openid, WeiXinUtil.getAccessToken(appId, secret).getAccessToken());
				if(userInfo!=null && "1".equals(userInfo.getSubscribe())){//已关注
					logger.info("------------------已关注的跳转------------------");
					HttpRequest.redirectHttpUrl(request,response, Constants.WEB_CONTEXT_PATH+"#/PersonalCenter?id=1");
				}else{
					logger.info("------------------未关注的跳转------------------");
					HttpRequest.redirectHttpUrl(request,response, Constants.WEB_CONTEXT_PATH+"#/lo");
				}
			}
		}else{
			HttpRequest.redirectHttpUrl(request,response, Constants.WEB_CONTEXT_PATH+"#/PersonalCenter?id=1");
		}
	}
	
}
